package com.naiterui.ehp.bs.payment.service.impl;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.naiterui.ehp.bs.payment.entity.OrderSequence;
import com.naiterui.ehp.bs.payment.repository.IOrderSequenceRepository;
import com.naiterui.ehp.bs.payment.service.IOrderSnService;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * 订单号生成规则
 *
 * @author wangzehao
 */
@Slf4j
@Service
@AllArgsConstructor
public class OrderSnServiceImpl implements IOrderSnService {

    private final IOrderSequenceRepository orderSequenceRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String getPayInfoTradeSn(Integer orderType) {
        if (orderType == null || orderType > 9 || orderType < 0) {
            throw new IllegalStateException("orderType不正确");
        }
        // 预留类型(2位置) + 订单类型(1位) + 时间戳(13位) + 流水号(12位) ps: 0011490944305495000000000001
        StringBuilder orderSn = new StringBuilder();
        // 预留类型(2位置)
        orderSn.append("00");
        // 订单类型(1位)
        orderSn.append(orderType);
        // 时间戳(13位)
        orderSn.append(System.currentTimeMillis());
        long serialNumber = this.getOrderSequence();
        orderSn.append(String.format("%012d", serialNumber));
        log.debug("生成新的订单号，订单号类型:{} 订单号:{}", orderType, orderSn);
        return orderSn.toString();
    }

    /**
     * 根据MySQL数据库主键自增获取订单号，这样可以保证不重复
     *
     * @return 获取的数据库自增主键
     */
    private long getOrderSequence() {
        return this.orderSequenceRepository.save(new OrderSequence()).getId();
    }

}
